import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { Text, View, StyleSheet, Alert, ScrollView, ActivityIndicator, TouchableOpacity } from 'react-native';
import { Icon, List, ListItem, Button, SearchBar } from 'react-native-elements';
import Loader from './widgets/Loader';
import RefreshScrollView from './widgets/RefreshScrollView';
import InfiniteList from './widgets/InfiniteList';
import { listDevices, disconnect } from './printerUtils';
import { primaryColor, toast, isIOS, loadMoreData, executor, getDirection } from './utils';
import { Calendar, LocaleConfig } from 'react-native-calendars';
import moment from 'moment';
import Communications from 'react-native-communications';
import { MyJobQuery } from './graphql';

const styles = StyleSheet.create({
  button: {
    marginVertical: 32
  },
  config: {
    margin: 16
  },
  header: {
    padding: 8
  },
  list: {
    marginTop: 0
  },
  ongoing: {
    backgroundColor: '#FFF3E0'
  },
  finished: {
    backgroundColor: '#E8F5E9'
  },
  spinner: {
    margin: 64
  },
  padding: {
    marginVertical: 32
  }
});

class MyJobPage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    return {
      title: screenProps.chinese?`我的工作`:`My Jobs`,
      tabBarLabel: screenProps.chinese?`我的工作`:`My Jobs`,
      tabBarIcon: ({tintColor}) => <Icon name='date-range' color={tintColor} size={24}/>
    };
  }
  state = { }
  // componentWillReceiveProps(nextProps) {
  //   if (nextProps.workingDays&&nextProps.workingDays[0]&&nextProps.orders&&!nextProps.orders[0]&&
  //     moment(nextProps.navigation.state.params&&nextProps.navigation.state.params.date).format('YYYY-MM-DD')!==moment(nextProps.workingDays[0]).format('YYYY-MM-DD')) {
  //     this.props.navigation.setParams({date:nextProps.workingDays[0]});
  //   }
  // }
  onSelectDate = ({year, month, day}) => {
    const date = moment([year, month-1, day]).toDate().toString();
    this.props.navigation.setParams({date});
  }
  onSearch = (search) => {
    this.props.refetch({search})
      .then(() => this.setState({searching: false}));
    this.setState({searching: true});
  }
  renderItem = ({item}) => {
    const {shipping, pricing: {details}, orderTypeDescription} = item;
    return <ListItem subtitle={`${orderTypeDescription}\r\n${shipping.address} ${shipping.postalCode} [${shipping.contactName}]`}
      title={`${details[0].description} x ${details[0].quantity} ${details[0].quantityUnit}${details[0].subDescription?`. ${details[0].subDescription}`:''}`}
      titleNumberOfLines={4} subtitleNumberOfLines={4} onPress={()=>this.getJob(item)} rightIcon={{name:'check-box-outline-blank'}}
      containerStyle={styles.availableJob}/>;
  }
  getJob = ({displayId, shipping, pricing: {details}, orderTypeDescription}) => {
    Alert.alert(
      this.props.screenProps.chinese?`确定要领取这份工作么？`:`Are you sure you want to get this job?`,
      `${details[0].description} x ${details[0].quantity} ${details[0].quantityUnit}${details[0].subDescription?`. ${details[0].subDescription}`:''}\r\n${orderTypeDescription}\r\n${shipping.address} ${shipping.postalCode} [${shipping.contactName}]`,
      [
        {text: this.props.screenProps.chinese?'取消':'Cancel'},
        {text: this.props.screenProps.chinese?'领取':'Get', onPress: () => {
          executor(this.props.selfAssignOrder, displayId)
            .then(({res}) => {
              if (res) {
                toast(this.props.screenProps.chinese?'工作获取成功':'Get job succeed', true);
              }
            });
          toast(this.props.screenProps.chinese?'工作获取中，请稍后...':'Getting the job...', true);
        }},
      ],
      { cancelable: true }
    );
  }
  onCall = (shipping) => {
    Communications.phonecall(shipping.contact, false);
  }
  onStart = (id) => {
    const chinese = this.props.screenProps.chinese;
    this.onSubmit(this.props.updateOrderStatus, {orderId:id,statusId:6}, chinese?'开始工作？':`Start the job?`, chinese?'开始':'Start', chinese?'工作已开始':'Job started');
  }
  onGiveup = (id) => {
    const chinese = this.props.screenProps.chinese;
    this.onSubmit(this.props.updateOrderStatus, {orderId:id,statusId:5,resetWorker:true}, chinese?`[警告] 你确定要放弃这个工作么？`:`[WARNING] Are you sure you want to give up this job?`, chinese?'放弃工作':'Give Up This Job', chinese?'工作已放弃':'Job gived up', 'destructive');
  }
  onFinished = (id) => {
    const chinese = this.props.screenProps.chinese;
    this.onSubmit(this.props.confirmDelivery, {orderId:id}, chinese?`完成工作？`:`Job finished?`, chinese?'完成工作':'Finish Job', chinese?'工作已完成':'Job finished');
  }
  onSubmit = (action, variables, title, okbutton, success, style) => {
    Alert.alert(
      title,
      null,
      [
        {text: this.props.screenProps.chinese?'取消':'Cancel'},
        {text: okbutton, style, onPress: () => {
          executor(action, variables)
            .then(({res}) => {
              if (res) {
                toast(success);
              }
            });
          toast(this.props.screenProps.chinese?'处理中...':'Submitting...');
        }},
      ],
      { cancelable: true }
    );
  }
  render() {
    const { navigation, screenProps, refetch, fetchMore, loading, orders } = this.props;
    const { selects, date, selectWorker } = navigation.state.params||{};
    const { chinese } = screenProps;
    const selectDate = date?moment(date):moment();

    return (
      <RefreshScrollView refetch={refetch}>
        <Calendar hideExtraDays markedDates={this.props.markedDates} theme={{
          selectedDayBackgroundColor: primaryColor,
          todayTextColor: primaryColor,
          dotColor: primaryColor,
          arrowColor: primaryColor,}}
          selected={[selectDate.format('YYYY-MM-DD')]} onDayPress={this.onSelectDate}
          onMonthChange={this.onSelectDate} displayLoadingIndicator={loading}/>
        {(loading&&!this.state.searching)?<ActivityIndicator size='large' style={styles.spinner}/>:(
          (!orders||orders.length===0)?<List><ListItem title={`${selectDate.format('DD/MM/YYYY')} ${screenProps.chinese?'没有工作':'Job Empty'}`} hideChevron/></List>:
            orders.map(({id, displayId, status:{statusId}, shipping, pricing: {details}, orderTypeDescription}, index) => {
              let backgroundStyle;
              if (statusId===6) {
                backgroundStyle = styles.ongoing;
              } else if (statusId===7||statusId===8) {
                backgroundStyle = styles.finished;
              }

              return (
                <List key={index}>
                  <View>
                    <ListItem leftIcon={{name:'access-time',color:'#FF5722'}} title={shipping.displayDate}
                      containerStyle={backgroundStyle} hideChevron/>
                    <ListItem subtitle={`${orderTypeDescription}\r\n${shipping.unitNumber}, ${shipping.address} ${shipping.postalCode} [${shipping.contactName} ${shipping.contact}]`}
                      title={`${chinese?'工作号':'Job Number'}: #${displayId}\r\n${details[0].description} x ${details[0].quantity} ${details[0].quantityUnit}${details[0].subDescription?`. ${details[0].subDescription}`:''}`}
                      titleNumberOfLines={4} subtitleNumberOfLines={4} hideChevron containerStyle={backgroundStyle}/>
                    <ListItem leftIcon={{name:'call',color:'#4CAF50'}} title={chinese?'呼叫客户':'Call Customer'}
                        containerStyle={backgroundStyle} hideChevron onPress={()=>this.onCall(shipping)}/>
                    {statusId===5&&
                      <ListItem leftIcon={{name:'play-arrow',color:'#4CAF50'}} title={chinese?'开始工作':'Start Job'}
                        containerStyle={backgroundStyle} hideChevron onPress={()=>this.onStart(id)}/>
                    }
                    {(statusId===5||statusId===6)&&
                      <ListItem leftIcon={{name:'directions',color:'#2196F3'}} title={chinese?'地图导航':'Map Direction'}
                        containerStyle={backgroundStyle} onPress={()=>getDirection({shipping})}/>
                    }
                    {statusId===5&&
                      <ListItem leftIcon={{name:'delete-forever',color:'#F44336'}} title={chinese?'放弃工作':'Give Up This Job'}
                        containerStyle={backgroundStyle} hideChevron onPress={()=>this.onGiveup(id)}/>
                    }
                    {statusId===6&&
                      <ListItem leftIcon={{name:'stop',color:'#FF5722'}} title={chinese?'完成':'Finish'}
                        containerStyle={backgroundStyle} hideChevron onPress={()=>this.onFinished(id)}/>
                    }
                  </View>
                </List>
              );
            })
        )}
        <View style={styles.padding}/>
      </RefreshScrollView>
    );
  }
}

function getVariables({state:{params}}) {
  const {search, offset=0, limit, date=moment([moment().year(),moment().month(),1]).toDate().toString()} = params||{};
  return {
    search,
    offset,
    limit,
    date,
    type: 'houseclean'
  };
}

export default compose(
  graphql(MyJobQuery, {
    options: ({navigation}) => ({variables: getVariables(navigation)}),
    props: ({data:{orders, loading, workingDays, fetchMore, refetch}}) => {
      let markedDates = {};
      if (workingDays) {
        workingDays.map(date => {
          markedDates[moment(date).format('YYYY-MM-DD')] = {marked: true};
        });
      }

      return {
        markedDates,
        orders,
        loading,
        refetch,
        workingDays,
        fetchMore: () => loadMoreData(fetchMore, orders, 'orders')
      };
    }
  }),
  graphql(gql`
    mutation updateOrderStatus($orderId:String!,$statusId:Int!,$resetWorker:Boolean) {
      updateOrderStatus(orderId:$orderId,statusId:$statusId,resetWorker:$resetWorker) {
        id
        status {
          statusId
        }
      }
    }
  `, {
    name: 'updateOrderStatus',
    props: ({ownProps:{navigation}, updateOrderStatus}) => {
      return {
        updateOrderStatus: (variables) => updateOrderStatus({
          variables,
          refetchQueries: ['MyJobQuery', 'JobPollQuery']
        })
      };
    }
  }),
  graphql(gql`
    mutation confirmDelivery($orderId:String!) {
      confirmDelivery(orderId:$orderId) {
        id
        status {
          statusId
        }
      }
    }
  `, {
    name: 'confirmDelivery',
    props: ({ownProps:{navigation}, confirmDelivery}) => {
      return {
        confirmDelivery: (variables) => confirmDelivery({
          variables,
          refetchQueries: [{
            query: MyJobQuery,
            variables: getVariables(navigation)
          }]
        })
      };
    }
  }),
)(MyJobPage);

